<?php

namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller {
    //用户登录页面
    public function login() {
        //用户的登录检测
        $id = $_SESSION['home']['uid'];
        //判断
        if (!empty($id)) {
            $this->error('您已经登录了呢!', U('News/index'));
            die;
        }

        $this->assign('test', '用户登录页面');
        $this->assign('ajaxurl', U('Login/logindo'));
        $this->assign('yesstr', '登录成功!');
        $this->assign('nostr', '登录失败!');
        $this->assign('lesstr', '请确保帐号为锁定且已验证邮箱!!');
        $this->display();
    }

    //极验验证
    public function jyan() {
        require_once '/Public/Jyan/lib/class.geetestlib.php';
        require_once '/Public/Jyan/config/config.php';
        $GtSdk = Jy(CAPTCHA_ID, PRIVATE_KEY);
        session_start();
        // $user_id             = mt_rand();
        $status               = $GtSdk->pre_process($user_id);
        $_SESSION['gtserver'] = $status;
        // $_SESSION['user_id'] = $user_id;
        echo $GtSdk->get_response_str();
    }

    //用户登录处理页面
    public function logindo() {
        //这里请使用ajax访问
        if (IS_AJAX) {
            //实例化数据表对象
            $user = M('User');
            // var_dump($_POST);die;
            //核实用户信息
            //处理得到的用户账号密码
            session_start();
            $test                     = I('post.pd');
            $data['zz_user.username'] = htmlspecialchars($test[0]);
            $data['zz_user.password'] = md5($test[1]);
            // $datapd = !empty($test[2]) ? true : false;
            //查询结果
            $res = $user
                ->where($data)
                ->join('zz_user_info ON zz_user.user_id  = zz_user_info.user_id')
                ->select();
            $res = $res[0];
            // echo $user -> _sql();
            // var_dump($res);die;
            if ($_SESSION['gtserver'] == 1) {
                if ($res) {
                    //判断帐号未被锁定 并且 邮箱以验证
                    // echo $res['email_state'];die;
                    if ($res['lock'] <= 10 and $res['email_state'] == 1) {
                        //在SESSION中记录用户的信息
                        $_SESSION['home']['uid']      = $res['user_id'];
                        $_SESSION['home']['uname']    = $res['username'];
                        $_SESSION['home']['nickname'] = $res['nickname'];
                        $_SESSION['home']['photo']    = $res['photo'];
                        //修改最后登录的时间和登录的IP
                        $arr = array(
                            'user_id'  => $_SESSION['home']['uid'],
                            'lasttime' => $_SERVER['REQUEST_TIME'],
                            'lastip'   => $_SERVER['REMOTE_ADDR'],
                            'online'   => '1',
                        );
                        $user->save($arr);
                        //当登录成功的时候
                        echo 'yes';
                        die;
                    } else {
                        //当帐号被锁定 或者邮箱未验证时
                        echo 'les';
                    }
                } else {
                    //数据库中没有匹配的数据时
                    echo 'no';
                }
            }
        } else {
            //当用户使用非ajax方式访问时
            $this->error('非法操作');
        }
    }

    //用户登出处理页面
    public function signout() {
        //清空SESSION内容
        session_unset();
        session_destroy();
        //跳转到登录页面
        $this->success('登出成功! 正在跳转到登录页面~', U('Login/login'), 2);
    }

    //用户注册页面
    public function signup() {
        $this->assign('title', '用户注册页面');
        $this->display();
    }

    //用户注册处理用ajax脚本
    public function signupdo() {
        $user = M('User');
        $user->startTrans();

        //准备用户基本数据
        $nowTime  = $_SERVER['REQUEST_TIME'];
        $nowIp    = $_SERVER['REMOTE_ADDR'];
        $username = I('post.username');
        $password = I('post.password');
        $userBase = array(
            'username'    => $username,
            'password'    => md5($password),
            'regtime'     => $nowTime,
            'regip'       => $nowIp,
            'lasttime'    => $nowTime,
            'lastip'      => $nowIp,
            'lock'        => 0,
            'email_token' => md5($username . $password),
            'email_state' => 0,
            'online'      => 0,
        );
        // var_dump($userBase);

        //自动验证
        $rules = array(
            array('username', 'email', '请填写正确的邮箱！'),
            array('username', '', '邮箱已经存在！', 0, 'unique', 1),
            array('password', 'require', '请填写密码！'),
        );

        //验证入库用户基本信息
        if ($user->validate($rules)->create($userBase)) {
            $id = $user->add();
        } else {
            $this->error($user->getError());
        }

        //准备用户详细信息
        $userInfo = array(
            'user_id'   => $id,
            'tag_id'    => '',
            'nickname'  => I('post.nickname'),
            'sex'       => I('post.sex', '2'),
            'area'      => '',
            'birthday'  => I('post.birthday'),
            'signature' => I('post.signature'),
            'photo'     => '/Resource/default_photo.png',
        );
        //自动验证
        $rules = array(
            array('nickname', 'require', '请填写您的昵称！'),
        );
        //验证入库用户详细信息
        $info = M('UserInfo');
        if ($userInfo = $info->validate($rules)->create($userInfo)) {
            if ($info->add()) {
                $user->commit();
                $title      = '欢迎注册众众网(请不要回复此邮件)';
                $activeLink = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . U('Home/login/email', array('token' => $userBase['email_token']));
                $content    = '<table style="margin: 25px auto;" border="0" cellspacing="0" cellpadding="0" width="648" align="center">
    <tbody>
    <tr><td style ="color:#2590BC;"><h1 style="margin-bottom:10px;">众众网</h1></td></tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 20px 20px 0px; background: none repeat scroll 0% 0% #ffffff; border-top: 5px solid #2590BC; border-right: 1px solid #66ABC7;">
    <p>' . $userInfo['nickname'] . ', 你好 </p>
    </td>
    </tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 10px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <p>您已经成功注册为<strong>众众网</strong>用户！</p>
    <p style="font-weight:bold">请点击以下链接激活此帐号：<br>
        <a href="' . $activeLink . '">' . $activeLink . '</a></p>
    </td>
    </tr>
    <tr>
    <td style="border-bottom: 1px solid #66ABC7; border-left: 1px solid #66ABC7; padding: 0px 20px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <hr style="color:#ccc;">
    <p style="color:#2590BC;font-size:9pt;">想了解更多信息，请关注众众网</p>
    </td>
    </tr>
    </tbody>
    </table>';
                //发送邮件
                sendMail($userBase['username'], $title, $content);
                $this->success('注册成功！请留意您的邮箱以激活您的账号！', U('Home/Login/login'), 3);
            } else {
                $user->rollback();
                $this->error('出错了...', '', 3);
            }
        } else {
            $this->error($info->getError());
        }
    }

    //邮箱验证页
    public function email() {
        $this->assign('title', '邮箱验证');
        $this->display();
    }

    //邮箱验证处理
    public function emaildo() {
        $username = I('get.username');
        $token    = I('get.token');
        $user     = M('User');
        $result   = $user->where("username='%s' and email_token='%s'", $username, $token)->find();
        if ($result) {
            if ($result['email_state'] == 1) {
                $this->error('您的邮箱早已验证，请不要再来调戏本宝宝！', U('Home/Login/login'), 3);
            } else {
                $data = array(
                    'user_id'     => $result['user_id'],
                    'email_state' => 1,
                );
                $user->save($data);

                //初始化新用户数据表
                $albumsData1 = array(
                    'albums_name' => '贴图相册',
                    'albums_type' => 0,
                    'user_id'     => $result['user_id'],
                    'time'        => $_SERVER['REQUEST_TIME'],
                );
                $albumsData2 = array(
                    'albums_name' => '共享相册',
                    'albums_type' => 1,
                    'user_id'     => $result['user_id'],
                    'time'        => $_SERVER['REQUEST_TIME'],
                );
                $albums = M('albums');
                $albums->add($albumsData1);
                $albums->add($albumsData2);

                $this->success('邮箱验证成功！', U('Home/Login/login'), 3);
            }
        } else {
            $this->error('验证失败！请检查您的邮箱号!', '', 3);
        }
    }

    //重置密码页面
    public function repwd() {
        $this->assign('test', '重置密码页面');
        $a = 1;
        $b = 2;
        $this->display();
    }

    //重置密码处理用ajax脚本
    public function repwddo() {
        //这里请使用ajax访问
        // if (IS_AJAX) {}
        echo '重置密码处理用ajax脚本!';
    }
}
